<template>
  <div
    ref="chartRef"
    id="chart"
    :style="'width: 100%; height: ' + height"
  ></div>
</template> 

<script>
import { onMounted, onUnmounted, ref, inject, shallowRef } from "vue";
import * as echarts from "echarts";

export default {
  props: {
    chartData: {
      type: Object,
      default: () => [],
    },
    height: {
      type: String,
      default: "60%",
    },
  },
  setup(props) {
    const chartRef = shallowRef(null); // 用于引用图表 DOM 元素
    const chartInstance = shallowRef(null); // 用于存储图表实例
    const data = ref(props.chartData.dataY); // 用于存储更新后的数据
    const timer=ref(null); // 用于存储定时器

    const eventBus = inject("eventBus"); // 注入全局的 EventBus

    const xData = ref(props.chartData.dataX);
    let tabType = localStorage.getItem("tabType");
    let color,
      colorRGB = [];
    if (tabType == 1) {
      color = ["#96D3FF", "#5B8FFF", "#76EFD1", "#FFE96E", "#FFC494"];
      colorRGB = [
        { rgb1: "rgba(150, 211, 255, 0.3)", rgb2: "rgba(150, 211, 255, 0)" },
        { rgb1: "rgba(91, 143, 255, 0.3)", rgb2: "rgba(91, 143, 255, 0)" },
        { rgb1: "rgba(118, 239, 209, 0.3)", rgb2: "rgba(118, 239, 209, 0)" },
        { rgb1: "rgba(255, 233, 110, 0.3)", rgb2: "rgba(255, 233, 110, 0)" },
        { rgb1: "rgba(255, 196, 148, 0.3)", rgb2: "rgba(255, 196, 148, 0)" },
      ];
    } else {
      color = ["#8EEB6D", "#3D91FF", "#68F5D7", "#F7B99A", "#A6A8F8"];
      colorRGB = [
        { rgb1: "rgba(142, 235, 109, 0.3)", rgb2: "rgba(142, 235, 109, 0)" },
        { rgb1: "rgba(61, 145, 255, 0.3)", rgb2: "rgba(61, 145, 255, 0)" },
        { rgb1: "rgba(104, 245, 215, 0.3)", rgb2: "rgba(104, 245, 215, 0)" },
        { rgb1: "rgba(247, 185, 154, 0.3)", rgb2: "rgba(247, 185, 154, 0)" },
        { rgb1: "rgba(166, 168, 248, 0.3)", rgb2: "rgba(166, 168, 248, 0)" },
      ];
    }

    // 初始化图表的方法
    const initChart = () => {
      if (!chartRef.value) return; // 确保 chartRef 已经绑定了 DOM 元素
      chartInstance.value = echarts.init(chartRef.value);

      const series = data.value.map((item, index) => ({
        name: item.name,
        type: "line",
        smooth: true,
        showSymbol: false,
        data: item.val,
        itemStyle: { color: color[index] },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: colorRGB[index].rgb1 },
            { offset: 1, color: colorRGB[index].rgb2 },
          ]),
        },
      }));

      const options = {
        tooltip: {
          trigger: "axis",
          transitionDuration: 0, //[defaule:0.4] echart防止tooltip的抖动
          axisPointer: { type: "line" },
          backgroundColor: "rgba(4, 42, 60, 0.8)",
          borderColor: "#3fbfea",
          borderWidth: 1,
          confine: true, //设置tooltip不超出图表
          textStyle: {
            color: "#fff",
            fontFamily: "MiSans-Medium",
            fontSize: 13,
          },
          formatter: function (params) {
            let result = `<b class="title-color">地市电力碳排放因子</b><br/>`;
            params.forEach((item) => {
              result += `<div class="text-color"> ${item.marker} ${item.seriesName}: <b>${item.value}</b></div>`;
            });
            return result;
          },
          axisPointer: {
            type: "cross",
            label: {
              backgroundColor: "rgba(49, 98, 91, 0.7)",
              borderColor: "#83ffee",
              color: "#00ffdd",
            },
          },
        },
        legend: {
          data: data.value.map((item) => item.name),
          show: true,
          left: "200px",
          top: 0,
          itemWidth: 9,
          itemHeight: 2,
          icon: "rect",
          orient: "horizontal",
          textStyle: {
            color: "#FFFFFF",
            fontSize: 14,
            fontFamily: "MiSans-Medium",
          },
          itemGap: 15,
        },
        grid: {
          left: "6%",
          top: "15%",
          right: "1%",
          bottom: "5%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: xData.value,
            boundaryGap: false,//x轴两边留白 true为留白
            splitLine: { show: false },
            axisLine: {
              show: true,
              lineStyle: { color: "rgba(130,144,157,0.1)", type: "solid" },
            },
            axisLabel: {
              interval: 0,
              rotate: 60,
              color: "#fff",
              fontSize: 14,
            },
            axisTick: { show: false },
            splitArea: { show: false },
          },
        ],
        dataZoom: [
          {
            xAxisData: 0, //这里是从X轴的0刻度开始
            show: false, //是否显示滑动条
            type: "slider", // 这个 dataZoom 组件是 slider 型 dataZoom 组件
            startValue: 0, // 从头开始。
            endValue: 11, // 一次性展示12个。
          },
        ],
        yAxis: [
          {
            name: "单位：kg CO2/kWh",
            nameTextStyle: {
              fontSize: 14,
              color: "#fff",
              padding: [0, 0, 20, 80],
            },
            nameLocation: "end",
            nameGap: 0,
            splitArea: { show: false },
            type: "value",
            splitLine: {
              show: true,
              lineStyle: {
                width: 2,
                type: "solid",
                color: "rgba(130,144,157,0.1)",
              },
            },
            axisLabel: { color: "#fff", fontSize: 14 },
            axisLine: { lineStyle: { color: "#fff" } },
             scale: true, //y轴数值自适应 不从0开始
          },
        ],
        series,
      };

      chartInstance.value.setOption(options);
      window.addEventListener("resize", chartInstance.value.resize);
      timer.value = setInterval(function () {
        if (xData.value.length < 11) {
          return;
        } else {
          // 每次向后滚动一个，最后一个从头开始。
          if (options.dataZoom[0].endValue == xData.value.length) {
            options.dataZoom[0].endValue = 11;
            options.dataZoom[0].startValue = 0;
          } else {
            options.dataZoom[0].endValue = options.dataZoom[0].endValue + 1;
            options.dataZoom[0].startValue = options.dataZoom[0].startValue + 1;
            if (options.dataZoom[0].endValue == xData.value.length) {
              options.dataZoom[0].endValue = 11;
              options.dataZoom[0].startValue = 0;
            }
          }
          chartInstance.value.setOption(options);
        }
      }, 2000);
    };

    onMounted(() => {
      initChart(); // 初始化图表
      window.addEventListener(
        "resize",
        () => chartInstance.value && chartInstance.value.resize()
      );
    });

    onUnmounted(() => {
      // 清除事件监听器
      window.removeEventListener("resize", chartInstance.value.resize);
      eventBus.off("updateData");
      clearInterval(timer.value);
    });

    return {
      chartRef,
    };
  },
};
</script>

<style lang="scss" scoped>
#chart {
  background-color: rgba(29, 52, 81, 0.2); /* 设置图表背景色 */
  padding-top: 20px;
}
::v-deep .title-color {
  color: #68fff5;
  font-size: 13px;
  height: 17px;
  line-height: normal;
  font-family: MiSans;
  font-weight: 630;
}
::v-deep .text-color {
  color: #fff;
  font-size: 14px;
  height: 17px;
  line-height: normal;
  font-family: MiSans;
  font-weight: 630;
  margin: 10px 0;
}
</style>
